package com.example.user.service.application.service;

import com.example.user.service.application.command.UserLoginCommand;
import com.example.user.service.application.port.in.UserLoginUseCase;
import com.example.user.service.common.JwtUtil;
import com.example.user.service.domain.User;
import com.example.user.service.domain.port.GetUserByNamePort;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserLoginService implements UserLoginUseCase {

    @Resource
    private GetUserByNamePort getUserByNamePort;

    @Override
    public String login(UserLoginCommand userLoginCommand) {
        //验证用户
        User user = User.getUserByName(userLoginCommand.name(), getUserByNamePort);
        log.info("user:{}", user);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
        //验证密码
        if(!user.validatePassword(userLoginCommand.password())){
            throw new RuntimeException("密码错误");
        }
        // 签发token
        String token = JwtUtil.generateToken(
                user.getId().id(),
                user.getName().username(),
                user.getIsSuper().value()
        );
        log.info("生成的JWT令牌: {}", token);
        return token;
    }
}
